<?php
include_once('../lib/Sqlexecutor.php');
include_once('../lib/Login.php');
include_once('../lib/TileUserInfo.php');
include('log4php/Logger.php');

Logger::configure('config.ini');
$logger = Logger::getLogger('intf');

$usrid = isset($_REQUEST['usrid']) ? $_REQUEST['usrid'] : 0;
$sessionid = isset($_REQUEST['sessionid']) ? $_REQUEST['sessionid'] : '';
$tile_id = isset($_REQUEST['tileid']) ? $_REQUEST['tileid'] : 0;
$series_id = isset($_REQUEST['seriesid']) ? $_REQUEST['seriesid'] : 0;
$score = isset($_REQUEST['score']) ? $_REQUEST['score'] : 0;
$price = isset($_REQUEST['price']) ? $_REQUEST['price'] : 0;


//login
$dbh = new Sqlexecutor('localhost', 'tile', 'tile', 'tile');
$usrid = isset($_REQUEST['usrid']) ? $_REQUEST['usrid'] : 0;
$sessionid = isset($_REQUEST['sessionid']) ? $_REQUEST['sessionid'] : '';

$l = new Login($dbh, $logger);
$info = $l->isLogin($usrid, $sessionid);
if($info != 1)
{
    $res['errno'] = -1;
    $output = json_encode($res); 
    $logger->trace("input: usrid=$usrid, sessionid=$sessionid; res: $output"); 
    echo $output;
    exit;
}

if($tile_id == 0 || $series_id == 0)
{
    $res['errno'] = -3; 
    $output = json_encode($res); 
    $logger->trace("input: usrid=$usrid, sessionid=$sessionid; res: $output"); 
    echo $output;
    exit;
}

$s = new TileUserInfo($dbh, $logger);
$info = $s->getInfoByTileId($usrid, $tile_id);

if($info === false)
{
    $res['errno'] = -100;
}
elseif($info === NULL)
{
    $r = $s->createInfo($usrid, $tile_id, $series_id, $price, $score);
    if($r > 0)
    {
        $res['errno'] = 0;
    }
    else
    {
        $res['errno'] = -100;
    }
}
else
{
    $r = $s->updateByTileID($usrid, $tile_id, $series_id, $price, $score);
    if($r == 1 || $r == 0)
    {
        $res['errno'] = 0;
    }
    else
    {
        $res['errno'] = -100;
    }

}
$output = json_encode($res);
$logger->trace("input: tile_id=$tile_id, usrid=$usrid, series_id=$series_id, price=$price, score=$score; res: $output"); 
echo $output;
